package com.xiyuan.smartutils.client.ws.core;

import java.nio.ByteBuffer;

import static com.xiyuan.smartutils.constants.SignConstants.MiB;

/**
 * Fragmented buffer management class management fragment buffer and recycle it
 * if occur fragmented buffer when received websocket data.
 *
 * @author xiyuan
 */
public class BufferManager {
    
    /**
     * The fragment buf.
     */
    private ByteBuffer fragmentBuf;
    
    /**
     * init management fragment buffer.
     */
    public void reset() {
        if (this.fragmentBuf != null && fragmentBuf.capacity() < 50 * MiB) {
            this.fragmentBuf.clear();
        }
        else {
            this.fragmentBuf = null;
        }
        
    }
    
    /**
     * Get merged fragmented buffer and argument buffer. if does not have a
     * management fragment buffer then return take a argument buffer
     *
     * @param buffer the buffer
     * @return merged buffer management(if have) and argument.
     */
    public ByteBuffer merge(ByteBuffer buffer) {
        if (fragmentBuf != null) {
            ByteBuffer buf = ByteBuffer.allocate(fragmentBuf.rewind().remaining() + buffer.remaining());
            buf.put(fragmentBuf);
            buf.put(buffer);
            buf.flip();
            
            buffer = buf;
        }
        return buffer;
    }
    
    /**
     * set buffer to management buffer.
     *
     * @param buffer the buffer
     */
    public void storeFragmentBuffer(ByteBuffer buffer) {
        this.fragmentBuf = ByteBuffer.allocate(buffer.remaining());
        this.fragmentBuf.put(buffer);
    }
}
